package servlets;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import actionForm.FindContactValidationForm;
import domain.Contact;
import domain.IDAOContact;

public class FindContactAction extends Action {
	public ActionForward execute(final ActionMapping pMapping,
			ActionForm pForm, final HttpServletRequest request,
			final HttpServletResponse response) {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		IDAOContact dao = (IDAOContact) context.getBean("daocontact");
		if (request.getMethod().equals("GET")){

			FindContactValidationForm form = (FindContactValidationForm) pForm;
			String findBy = form.getFindBy();
			ArrayList<Contact> foundContacts = new ArrayList<Contact>();
			if ( findBy.equals("email"))
			{
				foundContacts = dao.getContactByEmail(form.getEmail());
			}
			else if(findBy.equals("firstName"))
			{
				foundContacts = dao.getContactByFirstName(form.getFirstName());
			}
			else
			{
				foundContacts = dao.getContactByLastName(form.getLastName());
			}
			System.out.println("Hey");
			request.setAttribute("contacts", foundContacts.toArray());
			return pMapping.findForward("indexContacts");
		}
		return null;
	}
}